<template>
	<view class="page">
		<view class="container">
			<view class="header">
				<image class="logo" src="/static/login.png" mode="aspectFit"></image>
				<text class="title">智能直播课堂</text>
			</view>

			<view class="login-box">
				<view class="tab-wrapper">
					<view :class="['tab-item', activeTab === 'password' ? 'active' : '']" @tap="switchTab('password')">
						账号登录</view>
					<view :class="['tab-item', activeTab === 'sms' ? 'active' : '']" @tap="switchTab('sms')">验证码登录</view>
				</view>

				<view class="form">
					<!-- 账号登录表单 -->
					<view v-if="activeTab === 'password'">
						<view class="input-item">
							<view class="input-wrapper">
								<uni-icons class="input-icon" type="person" color="#666666" size="18"></uni-icons>
								<input class="uni-input" v-model="username" placeholder="请输入账号" />
							</view>
						</view>
						<view class="input-item">
							<view class="input-wrapper">
								<uni-icons class="input-icon" type="locked" color="#666666" size="18"></uni-icons>
								<input class="uni-input" v-model="password" password placeholder="请输入密码" />
							</view>
						</view>
					</view>

					<!-- 验证码登录表单 -->
					<view v-if="activeTab === 'sms'">
						<view class="input-item">
							<view class="input-wrapper">
								<uni-icons class="input-icon" type="phone" color="#666666" size="18"></uni-icons>
								<input class="uni-input" v-model="phone" placeholder="请输入手机号" maxlength="11" />
							</view>
						</view>
						<view class="input-item">
							<view class="input-wrapper">
								<uni-icons class="input-icon" type="checkmarkempty" color="#666666" size="18"></uni-icons>
								<input class="uni-input" v-model="verifyCode" placeholder="请输入4位验证码" maxlength="4" />
								<text class="sms-btn" :class="{ disabled: smsCountdown > 0 }" @tap="getSmsCode">
									{{ smsCountdown > 0 ? smsCountdown + 's后重发' : '获取验证码' }}
								</text>
							</view>
						</view>
					</view>

					<button class="login-btn" type="primary" @tap="handleLogin">登录</button>

					<view class="helper-links">
						<text class="link" @tap="toRegister">注册账号</text>
						<text class="link" @tap="toForgetPassword">忘记密码</text>
					</view>
				</view>

				<view class="other-login">
					<view class="divider">
						<text class="divider-text">其他登录方式</text>
					</view>
					<view class="wechat-login" @tap="handleWechatLogin">
						<image class="wechat-icon" src="/static/weix.png" mode="aspectFit"></image>
						<text class="wechat-text">微信登录</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { API_BASE_URL } from '../../static/constants'
	
export default {
	data() {
		return {
			activeTab: 'password', // 'password' 或 'sms'
			username: '', // 账号登录用户名
			password: '', // 账号登录密码
			phone: '', // 手机号
			verifyCode: '', // 验证码
			smsCountdown: 0, // 短信倒计时
			smsTimer: null // 短信定时器
		}
	},
	
	onLoad() {
		// 监听注册成功事件
		uni.$on('registerSuccess', this.handleRegisterSuccess);
	},
	
	onUnload() {
		// 移除事件监听
		uni.$off('registerSuccess', this.handleRegisterSuccess);
	},
	methods: {
		// 处理注册成功事件
		handleRegisterSuccess(data) {
			if (data && data.username) {
				// 自动填写用户名
				this.username = data.username;
				// 切换到密码登录标签
				this.activeTab = 'password';
				// 显示提示
				uni.showToast({
					title: '注册成功，请设置密码',
					icon: 'success',
					duration: 2000
				});
			}
		},
		
		switchTab(tab) {
			this.activeTab = tab;
			// 切换标签时清空输入
			this.username = '';
			this.password = '';
			this.phone = '';
			this.verifyCode = '';
		},

		handleLogin() {
			if (this.activeTab === 'password') {
				// 账号密码登录
				this.handlePasswordLogin();
			} else {
				// 验证码登录
				this.handleSmsLogin();
			}
		},

		handlePasswordLogin() {
			if (!this.username) {
				uni.showToast({
					title: '请输入账号',
					icon: 'none'
				});
				return;
			}
			if (!this.password) {
				uni.showToast({
					title: '请输入密码',
					icon: 'none'
				});
				return;
			}

			// 显示加载提示
			uni.showLoading({
				title: '登录中...'
			});

			// TODO: 后端接口 - 账号密码登录
			// POST /api/auth/login
			// 请求参数: { username: string, password: string }
			// 返回: { success: boolean, data: { token: string, userInfo: object }, message: string }
			
			// 检查是否是测试账号，直接处理
			if (this.username === '2025001' && this.password === 'admin77') {
				uni.hideLoading();
				// 测试账号1直接登录成功
				uni.setStorageSync('isLoggedIn', true);
				uni.setStorageSync('token', 'test_token_2025001');
				uni.setStorageSync('userInfo', {
					id: 2025001,
					username: '2025001',
					name: '测试管理员',
					phone: '13800138000',
					email: '2025001@example.com',
					avatar: '',
					role: 'admin'
				});
				
				uni.showToast({
					title: '测试账号1登录成功',
					icon: 'success'
				});
				
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/home/home'
					});
				}, 1500);
				return;
			} else if (this.username === '2025002' && this.password === '123456') {
				uni.hideLoading();
				// 测试账号2直接登录成功
				uni.setStorageSync('isLoggedIn', true);
				uni.setStorageSync('token', 'test_token_2025002');
				uni.setStorageSync('userInfo', {
					id: 2025002,
					username: '2025002',
					name: '测试用户',
					phone: '',
					email: '',
					avatar: '',
					role: 'user'
				});
				
				uni.showToast({
					title: '测试账号2登录成功',
					icon: 'success'
				});
				
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/home/home'
					});
				}, 1500);
				return;
			} else if (this.username === '202505048' || this.username === '2025048') {
				uni.hideLoading();
				// 测试账号3 - 坤坤鸡
				uni.setStorageSync('isLoggedIn', true);
				uni.setStorageSync('token', 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIyMDI1MDQ4IiwiaWF0IjoxNzU3NjU4Njc1LCJleHAiOjE3NTc3NDUwNzV9.95aCDBHTLtjMQu4kWP914-gq4J1l6sLgfBw2yENSCXc');
				uni.setStorageSync('userInfo', {
					id: '2025048',
					username: '202505048',
					name: '坤坤鸡',
					nickname: '坤坤鸡',
					phone: '13215485694',
					email: '',
					avatar: '',
					role: 1
				});
				
				uni.showToast({
					title: '坤坤鸡登录成功',
					icon: 'success'
				});
				
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/home/home'
					});
				}, 1500);
				return;
			}
			// 模拟API调用
			uni.request({
				url: API_BASE_URL+'9001/user/login', // 后端需要实现
				method: 'GET',
				data: {
					username: this.username,
					password: this.password
				},
				success: (res) => {
					uni.hideLoading();
					if (res.data.code === 200) {
						console.log(res.data.data);
						// 保存登录状态和用户信息
						uni.setStorageSync('isLoggedIn', true);
						uni.setStorageSync('token', res.data.data.token);
						uni.setStorageSync('userId', res.data.data.userId);
						console.log('user'+uni.getStorageSync('userId'));
						uni.showToast({
							title: '登录成功',
							icon: 'success'
						});
						
						// 跳转到首页
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/home/home'
							});
						}, 1500);
					} else {
						uni.showToast({
							title: res.data?.message || '登录失败',
							icon: 'none'
						});
					}
				},
				fail: (err) => {
					uni.hideLoading();
					console.error('登录请求失败:', err);
					// 开发阶段的模拟登录
					this.mockPasswordLogin();
				}
			});
		},

		handleSmsLogin() {
			if (!this.phone) {
				uni.showToast({
					title: '请输入手机号',
					icon: 'none'
				});
				return;
			}
			
			// 验证手机号格式
			const phoneRegex = /^1[3-9]\d{9}$/;
			if (!phoneRegex.test(this.phone)) {
				uni.showToast({
					title: '请输入正确的手机号',
					icon: 'none'
				});
				return;
			}

			if (!this.verifyCode) {
				uni.showToast({
					title: '请输入验证码',
					icon: 'none'
				});
				return;
			}

			if (this.verifyCode.length !== 4) {
				uni.showToast({
					title: '请输入4位验证码',
					icon: 'none'
				});
				return;
			}

			// 显示加载提示
			uni.showLoading({
				title: '登录中...'
			});

			// 模拟网络延迟
			setTimeout(() => {
				uni.hideLoading();
				
				// 直接处理验证码登录（开发阶段）
				uni.setStorageSync('isLoggedIn', true);
				uni.setStorageSync('token', 'test_token_sms_' + this.phone);
				uni.setStorageSync('userInfo', {
					id: Date.now(), // 使用时间戳作为临时ID
					phone: this.phone,
					name: '用户' + this.phone.slice(-4),
					username: this.phone,
					email: this.phone + '@example.com',
					avatar: '',
					role: 'user'
				});
				
				uni.showToast({
					title: '验证码登录成功',
					icon: 'success'
				});
				
				// 跳转到首页
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/home/home'
					});
				}, 1500);
			}, 1000);
		},

		getSmsCode() {
			if (this.smsCountdown > 0) {
				return; // 倒计时中不能重复发送
			}

			if (!this.phone) {
				uni.showToast({
					title: '请输入手机号',
					icon: 'none'
				});
				return;
			}
			
			// 验证手机号格式
			const phoneRegex = /^1[3-9]\d{9}$/;
			if (!phoneRegex.test(this.phone)) {
				uni.showToast({
					title: '请输入正确的手机号',
					icon: 'none'
				});
				return;
			}

			// 显示加载提示
			uni.showLoading({
				title: '发送中...'
			});

			// 模拟网络延迟
			setTimeout(() => {
				uni.hideLoading();
				
				// 生成4位随机验证码
				const verifyCode = this.generateRandomCode();
				
				// 开始倒计时
				this.startCountdown();
				
				// 显示验证码（开发阶段）
				uni.showToast({
					title: `验证码: ${verifyCode}`,
					icon: 'none',
					duration: 5000
				});
				
				// 自动填入验证码（开发阶段）
				setTimeout(() => {
					this.verifyCode = verifyCode;
				}, 1000);
				
				console.log(`手机号 ${this.phone} 的验证码: ${verifyCode}`);
			}, 1000);
		},

		// 生成4位随机验证码
		generateRandomCode() {
			return Math.floor(1000 + Math.random() * 9000).toString();
		},

		// 开始倒计时
		startCountdown() {
			this.smsCountdown = 60;
			this.smsTimer = setInterval(() => {
				this.smsCountdown--;
				if (this.smsCountdown <= 0) {
					clearInterval(this.smsTimer);
					this.smsTimer = null;
				}
			}, 1000);
		},

		// 开发阶段模拟方法
		mockPasswordLogin() {
			// 检查是否是测试账号
			if (this.username === '2025001' && this.password === 'admin77') {
				// 测试账号1登录成功
				uni.setStorageSync('isLoggedIn', true);
				uni.setStorageSync('token', 'test_token_2025001');
				uni.setStorageSync('userInfo', {
					id: 2025001,
					username: '2025001',
					name: '测试管理员',
					phone: '13800138000',
					email: '2025001@example.com',
					avatar: '',
					role: 'admin'
				});
				
				uni.showToast({
					title: '测试账号1登录成功',
					icon: 'success'
				});
				
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/home/home'
					});
				}, 1500);
			} else if (this.username === '2025002' && this.password === '123456') {
				// 测试账号2登录成功
				uni.setStorageSync('isLoggedIn', true);
				uni.setStorageSync('token', 'test_token_2025002');
				uni.setStorageSync('userInfo', {
					id: 2025002,
					username: '2025002',
					name: '测试用户',
					phone: '',
					email: '',
					avatar: '',
					role: 'user'
				});
				
				uni.showToast({
					title: '测试账号2登录成功',
					icon: 'success'
				});
				
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/home/home'
					});
				}, 1500);
			} else if (this.username === '202505048' || this.username === '2025048') {
				// 测试账号3 - 坤坤鸡
				uni.setStorageSync('isLoggedIn', true);
				uni.setStorageSync('token', 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIyMDI1MDQ4IiwiaWF0IjoxNzU3NjU4Njc1LCJleHAiOjE3NTc3NDUwNzV9.95aCDBHTLtjMQu4kWP914-gq4J1l6sLgfBw2yENSCXc');
				uni.setStorageSync('userInfo', {
					id: '2025048',
					username: '202505048',
					name: '坤坤鸡',
					nickname: '坤坤鸡',
					phone: '13215485694',
					email: '',
					avatar: '',
					role: 1
				});
				
				uni.showToast({
					title: '坤坤鸡登录成功',
					icon: 'success'
				});
				
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/home/home'
					});
				}, 1500);
			} else {
				// 其他账号的模拟登录
				uni.setStorageSync('isLoggedIn', true);
				uni.setStorageSync('userInfo', {
					username: this.username,
					name: '用户' + this.username,
					phone: '',
					email: this.username + '@example.com'
				});
				
				uni.showToast({
					title: '模拟登录成功',
					icon: 'success'
				});
				
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/home/home'
					});
				}, 1500);
			}
		},





		toRegister() {
			// 跳转注册页面
			uni.navigateTo({
				url: '/pages/enllo/enllo'
			});
		},

		toForgetPassword() {
			// 跳转忘记密码页面
			uni.showToast({
				title: '功能开发中',
				icon: 'none'
			});
		},

		handleWechatLogin() {
			// 处理微信登录逻辑
			uni.showToast({
				title: '微信登录功能开发中',
				icon: 'none'
			});
		}
	},
	
	onUnload() {
		// 页面卸载时清除定时器
		if (this.smsTimer) {
			clearInterval(this.smsTimer);
			this.smsTimer = null;
		}
	}
}
</script>

<style>
	page {
		height: 100%;
	}

	.page {
		height: 100%;
		background: linear-gradient(135deg, #1976D2 0%, #64B5F6 100%);
	}

	.container {
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 0 40rpx;
		box-sizing: border-box;
	}

	.header {
		margin-top: 120rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.logo {
		width: 120rpx;
		height: 120rpx;
		margin-bottom: 20rpx;
	}

	.title {
		font-size: 32px;
		color: #FFFFFF;
		font-weight: 500;
		margin-bottom: 80rpx;
	}

	.login-box {
		width: 100%;
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 40rpx;
		box-sizing: border-box;
	}

	.tab-wrapper {
		display: flex;
		margin-bottom: 60rpx;
	}

	.tab-item {
		flex: 1;
		text-align: center;
		font-size: 16px;
		color: #666666;
		padding-bottom: 20rpx;
		position: relative;
	}

	.tab-item.active {
		color: #1976D2;
		font-weight: 500;
	}

	.tab-item.active::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		width: 40rpx;
		height: 4rpx;
		background: #1976D2;
		border-radius: 2rpx;
	}

	.input-item {
		margin-bottom: 40rpx;
	}

	.input-wrapper {
		display: flex;
		align-items: center;
		border: 1px solid #DCDFE6;
		border-radius: 8rpx;
		padding: 0 20rpx;
	}

	.input-icon {
		width: 18px;
		height: 18px;
		margin-right: 20rpx;
	}

	.uni-input {
		flex: 1;
		height: 88rpx;
		font-size: 14px;
	}

	.sms-btn {
		font-size: 14px;
		color: #1976D2;
		padding: 0 20rpx;
		white-space: nowrap;
		transition: color 0.3s ease;
	}

	.sms-btn.disabled {
		color: #999999;
		cursor: not-allowed;
	}

	.login-btn {
		width: 100%;
		height: 88rpx;
		margin: 60rpx 0;
		font-size: 16px;
	}

	.helper-links {
		display: flex;
		justify-content: space-between;
		margin-bottom: 60rpx;
	}

	.link {
		font-size: 14px;
		color: #1976D2;
	}

	.divider {
		position: relative;
		text-align: center;
		margin-bottom: 60rpx;
	}

	.divider::before,
	.divider::after {
		content: '';
		position: absolute;
		top: 50%;
		width: 80rpx;
		height: 2rpx;
		background: #EEEEEE;
	}

	.divider::before {
		left: 50%;
		margin-left: -140rpx;
	}

	.divider::after {
		right: 50%;
		margin-right: -140rpx;
	}

	.divider-text {
		font-size: 14px;
		color: #999999;
		background: #FFFFFF;
		padding: 0 20rpx;
	}

	.wechat-login {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.wechat-icon {
		width: 56rpx;
		height: 56rpx;
		display: block;
		border: 1rpx solid transparent;
	}

	.wechat-text {
		font-size: 14px;
		color: #07C160;
		margin-top: 10rpx;
	}
</style>